package cn.itsource.pethome.user.service.impl;

import cn.itsource.pethome.Basic.util.HttpClientUtils;
import cn.itsource.pethome.Basic.util.RedisUtils;
import cn.itsource.pethome.Basic.util.StrUtils;
import cn.itsource.pethome.user.constant.PhoneConstant;
import cn.itsource.pethome.user.constant.WechatConstant;
import cn.itsource.pethome.user.domain.User;
import cn.itsource.pethome.user.domain.WechatUser;
import cn.itsource.pethome.user.domain.dto.WechatUserDto;
import cn.itsource.pethome.user.mapper.UserMapper;
import cn.itsource.pethome.user.mapper.WechatMapper;
import cn.itsource.pethome.user.service.IWechatService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Service
public class WechatServiceImpl implements IWechatService {
    @Autowired
    private WechatMapper wechatMapper;
    @Autowired
    private UserMapper userMapper;
    @Override
    public Map<String, Object> handleCallback(String code) {
        //获取token
        String tokenUtl = WechatConstant.TOKEN.replace("APPID", WechatConstant.APPID)
                .replace("SECRET", WechatConstant.SECRET)
                .replace("CODE", code);
        //通过http发送get请求
        String tokenStr = HttpClientUtils.httpGet(tokenUtl);
        System.out.println("------------"+tokenStr);
        //将token字符串转为json对象，以便获取openId和access_token
        //"access_token":"36_bGmw77Y2od6B1VwnZYA8VC"
        //"openid":"oa9wA01Aap-4yjUgGAkj4OVJi4pc"
        JSONObject jsonObject = JSON.parseObject(tokenStr);
        //获取access_token
        String access_token = jsonObject.getString("access_token");
        //获取openId
        String openid = jsonObject.getString("openid");
        //获取用户地址
        String userInfo = WechatConstant.USERINFO.replace("ACCESS_TOKEN", access_token)
                .replace("OPENID", openid);
        //发送get请求
        String userInfoStr = HttpClientUtils.httpGet(userInfo);
        System.out.println("================"+userInfoStr);
        //将用户地址字符串转换为json对象
        JSONObject userInfoObject = JSON.parseObject(userInfoStr);
        //通过openid查询微信登录用户数据库
        WechatUser wechatUser = wechatMapper.findByOpenid(openid);
        Map<String,Object> map = new HashMap<>();
        if(wechatUser==null){
            WechatUser user = new WechatUser();
            //获取国家、省、城市
            String country = userInfoObject.getString("country");
            String province = userInfoObject.getString("province");
            String city = userInfoObject.getString("city");
            user.setAddress(country+province+city);
            user.setHeadimgurl(userInfoObject.getString("headimgurl"));
            user.setNickname(userInfoObject.getString("nickname"));
            user.setOpenid(openid);
            user.setSex(userInfoObject.getInteger("sex"));
            user.setUnionid(userInfoObject.getString("unionid"));
            //将微信用户信息存储到数据库
            wechatMapper.save(user);
            //跳转绑定界面
            map.put("url",WechatConstant.REDIRECT_SERVER+WechatConstant.BINDER+"?openid="+openid);
            return map;
        }else{
            User u = wechatUser.getUser();
            //判断是否绑定
            if(u==null){
                //跳转绑定界面
                map.put("url",WechatConstant.REDIRECT_SERVER+WechatConstant.BINDER+"?openid="+wechatUser.getOpenid());
                return map;
            }else {
                //已绑定，直接登录
                //获取令牌
                String token = UUID.randomUUID().toString();
                //将用户信息保存到redis
                RedisUtils.INSTANCE.set("token",JSON.toJSONString(u),30*60);
                map.put("token",token);
                map.put("loginUser",u);
                return map;
            }
        }
    }

    @Override
    public Map<String, Object> binder(WechatUserDto wechatUserDto) {
        //获取账户名
        String username = wechatUserDto.getUsername();
        if(StringUtils.isEmpty(username)){
            throw new RuntimeException("用户名不能为空!!!!!");
        }
        if(StringUtils.isEmpty(wechatUserDto.getPassword())){
            throw new RuntimeException("密码不能为空!!!!!!");
        }
        //通过账户名查询用户
        User user = userMapper.checkPhone(username);
        Map<String,Object> map = new HashMap<>();
        //判断用户是否注册
        if(user==null){
            User u = new User();
            //注册用户用户名
            u.setUsername(username);
            //获取盐值
            String salt = StrUtils.getComplexRandomString(10);
            //注册盐值
            u.setSalt(salt);
            //注册用户密码
            u.setPassword(wechatUserDto.getPassword()+salt);
            //注册用户状态
            u.setState(PhoneConstant.ACTIVE);
            //注册用户
            userMapper.save(u);
            //绑定微信用户
            wechatMapper.binder(u.getId(),wechatUserDto.getOpenid());
            //获取token
            String token = UUID.randomUUID().toString();
            //保存数据到redis
            RedisUtils.INSTANCE.set(token,JSON.toJSONString(u),30*60);
            //将用户返回到前台，token令牌和用户
            map.put("token",token);
            map.put("loginUser",u);
            return map;
        }else{
            //如果有该用户，则需判断密码是否正确
            if(!user.getPassword().equals(wechatUserDto.getPassword()+user.getSalt())){
                throw new RuntimeException("密码错误!!!!!!");
            }
            //绑定微信用户
            wechatMapper.binder(user.getId(),wechatUserDto.getOpenid());
            //获取token
            String token = UUID.randomUUID().toString();
            //保存数据到redis
            RedisUtils.INSTANCE.set(token,JSON.toJSONString(user),30*60);
            //将用户返回到前台，token令牌和用户
            map.put("token",token);
            map.put("loginUser",user);
            return map;
        }
    }
}
